#include "errorhandler.h"
#include "constants.h"
#include <QApplication>
#include <QFileInfo>
#include <QDir>
#include <QStandardPaths>

namespace RestaurantSystem {

ErrorHandler& ErrorHandler::instance() {
    static ErrorHandler instance;
    return instance;
}

void ErrorHandler::handleError(ErrorLevel level, const QString& message, 
                              const QString& context, bool showToUser) {
    // 记录日志
    logMessage(level, message, context);
    
    // 如果需要显示给用户
    if (showToUser) {
        QString title;
        QMessageBox::Icon icon = getMessageBoxIcon(level);
        
        switch (level) {
            case ErrorLevel::INFO:
                title = "信息";
                break;
            case ErrorLevel::WARNING:
                title = "警告";
                break;
            case ErrorLevel::ERROR:
                title = "错误";
                break;
            case ErrorLevel::CRITICAL:
                title = "严重错误";
                break;
        }
        
        showUserMessage(message, icon, title);
    }
    
    // 严重错误时的特殊处理
    if (level == ErrorLevel::CRITICAL) {
        qCritical() << "严重错误:" << message << "上下文:" << context;
        // 可以在这里添加崩溃转储或紧急数据保存逻辑
    }
}

void ErrorHandler::logMessage(ErrorLevel level, const QString& message, const QString& context) {
    if (!m_loggingEnabled) {
        return;
    }
    
    QString formattedMessage = formatErrorMessage(level, message, context);
    
    // 输出到控制台
    switch (level) {
        case ErrorLevel::INFO:
            qInfo() << formattedMessage;
            break;
        case ErrorLevel::WARNING:
            qWarning() << formattedMessage;
            break;
        case ErrorLevel::ERROR:
            qCritical() << formattedMessage;
            break;
        case ErrorLevel::CRITICAL:
            qFatal("%s", formattedMessage.toUtf8().constData());
            break;
    }
    
    // 写入日志文件
    writeToLogFile(formattedMessage);
}

void ErrorHandler::showUserMessage(const QString& message, QMessageBox::Icon icon, const QString& title) {
    QMessageBox msgBox;
    msgBox.setIcon(icon);
    msgBox.setText(message);
    msgBox.setWindowTitle(title.isEmpty() ? Constants::APP_NAME : title);
    msgBox.setStandardButtons(QMessageBox::Ok);
    
    // 设置默认按钮
    msgBox.setDefaultButton(QMessageBox::Ok);
    
    // 如果有父窗口，设置为模态对话框
    if (QApplication::activeWindow()) {
        msgBox.setParent(QApplication::activeWindow());
        msgBox.setModal(true);
    }
    
    msgBox.exec();
}

bool ErrorHandler::showConfirmDialog(const QString& message, const QString& title) {
    QMessageBox msgBox;
    msgBox.setIcon(QMessageBox::Question);
    msgBox.setText(message);
    msgBox.setWindowTitle(title.isEmpty() ? "确认" : title);
    msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    msgBox.setDefaultButton(QMessageBox::No);
    
    // 设置按钮文本为中文
    msgBox.setButtonText(QMessageBox::Yes, "是");
    msgBox.setButtonText(QMessageBox::No, "否");
    
    if (QApplication::activeWindow()) {
        msgBox.setParent(QApplication::activeWindow());
        msgBox.setModal(true);
    }
    
    return msgBox.exec() == QMessageBox::Yes;
}

void ErrorHandler::writeToLogFile(const QString& message) {
    QMutexLocker locker(&m_logMutex);
    
    // 检查是否需要轮转日志文件
    rotateLogFileIfNeeded();
    
    QFile logFile(m_logFilePath);
    if (logFile.open(QIODevice::WriteOnly | QIODevice::Append)) {
        QTextStream stream(&logFile);
        stream << message << Qt::endl;
        logFile.close();
    }
}

void ErrorHandler::rotateLogFileIfNeeded() {
    QFileInfo fileInfo(m_logFilePath);
    if (!fileInfo.exists()) {
        return;
    }
    
    if (fileInfo.size() > m_maxLogFileSize) {
        // 创建备份文件名
        QString backupPath = QString("%1.%2")
            .arg(m_logFilePath)
            .arg(QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss"));
        
        // 重命名当前日志文件
        QFile::rename(m_logFilePath, backupPath);
        
        // 清理旧的备份文件
        cleanupLogFiles();
    }
}

void ErrorHandler::cleanupLogFiles() {
    QFileInfo logFileInfo(m_logFilePath);
    QDir logDir = logFileInfo.dir();
    QString baseName = logFileInfo.baseName();
    QString suffix = logFileInfo.suffix();
    
    // 查找所有备份文件
    QStringList filters;
    filters << QString("%1.*.%2").arg(baseName, suffix);
    
    QStringList backupFiles = logDir.entryList(filters, QDir::Files, QDir::Time | QDir::Reversed);
    
    // 删除超出限制的旧文件
    const int maxBackupFiles = 5; // 保留最近5个备份文件
    for (int i = maxBackupFiles; i < backupFiles.size(); ++i) {
        QString filePath = logDir.absoluteFilePath(backupFiles[i]);
        QFile::remove(filePath);
    }
}

QString ErrorHandler::errorLevelToString(ErrorLevel level) {
    switch (level) {
        case ErrorLevel::INFO: return "信息";
        case ErrorLevel::WARNING: return "警告";
        case ErrorLevel::ERROR: return "错误";
        case ErrorLevel::CRITICAL: return "严重错误";
        default: return "未知";
    }
}

QString ErrorHandler::formatErrorMessage(ErrorLevel level, const QString& message, const QString& context) {
    QString timestamp = QDateTime::currentDateTime().toString(Constants::LOG_DATE_FORMAT);
    QString levelStr = errorLevelToString(level);
    
    QString formatted = QString("[%1] [%2] %3")
        .arg(timestamp, levelStr, message);
    
    if (!context.isEmpty()) {
        formatted += QString(" (上下文: %1)").arg(context);
    }
    
    return formatted;
}

QMessageBox::Icon ErrorHandler::getMessageBoxIcon(ErrorLevel level) {
    switch (level) {
        case ErrorLevel::INFO:
            return QMessageBox::Information;
        case ErrorLevel::WARNING:
            return QMessageBox::Warning;
        case ErrorLevel::ERROR:
        case ErrorLevel::CRITICAL:
            return QMessageBox::Critical;
        default:
            return QMessageBox::NoIcon;
    }
}

QString fileOperationResultToString(FileOperationResult result) {
    switch (result) {
        case FileOperationResult::SUCCESS:
            return "操作成功";
        case FileOperationResult::FILE_NOT_FOUND:
            return "文件未找到";
        case FileOperationResult::PERMISSION_DENIED:
            return "权限不足";
        case FileOperationResult::DISK_FULL:
            return "磁盘空间不足";
        case FileOperationResult::CORRUPTED_DATA:
            return "数据已损坏";
        case FileOperationResult::UNKNOWN_ERROR:
        default:
            return "未知错误";
    }
}

} // namespace RestaurantSystem
